<?php
/**
 *    来自：信呼开发团队
 *    作者：磐石(rainrock)
 *    网址：http://www.rockoa.com/
 *    系统文件
 */

class xinhuapiChajian extends Chajian
{
    private $updatekey = '';
    private $updatekeys = '';
    private $systemnum = '';
    private $smsapikey = '';

    protected function initChajian()
    {
        if (getconfig('systype') == 'dev') {
            $this->updatekeys = 'aHR0cDovLzEyNy4wLjAuMS9hcHAvcm9ja2FwaS8:';
        } else {
            $this->updatekeys = 'aHR0cDovL2FwaS5yb2Nrb2EuY29tLw::';
        }
        $this->updatekey = $this->rock->jm->base64decode($this->updatekeys);
        $this->getsysnum();
    }

    private function getsysnum()
    {
        $dbs = m('option');
        $this->systemnum = $dbs->getval('systemnum');
        $this->smsapikey = $dbs->getval('sms_apikey');
        $this->qiannum = $dbs->getval('sms_qmnum');
        $this->sendtype = $dbs->getval('sms_dirtype');
        if (isempt($this->qiannum)) $this->qiannum = '';
        if (isempt($this->systemnum)) {
            $rnd = md5(str_shuffle('abcedfghijk') . rand(1000, 9999));
            $dbs->setval('systemnum', $rnd);
            $this->systemnum = $rnd;
        }
        return $this->systemnum;
    }

    public function geturlstr($mod, $act, $can = array())
    {
        $url = $this->updatekey;
        $url .= '?m=' . $mod . '&a=' . $act . '';
        $url .= '&host=' . $this->rock->jm->base64encode(HOST) . '&version=' . VERSION . '&randtime=' . time() . '&ip=' . $this->rock->ip . '&xinhukey=' . getconfig('xinhukey') . '&sysnum=' . $this->systemnum . '';
        if (!isempt($this->smsapikey)) $url .= '&smsapikey=' . $this->smsapikey . '';
        $url .= '&authorkey=' . getconfig('authorkey') . '';
        foreach ($can as $k => $v) $url .= '&' . $k . '=' . $v . '';
        return $url;
    }

    public function getdata($mod, $act, $can = array())
    {
        $url = $this->geturlstr($mod, $act, $can);
        $cont = c('curl')->getcurl($url);
        if (!isempt($cont) && contain($cont, 'success')) {
            $data = json_decode($cont, true);
        } else {
            $data = returnerror('无法访问到官网API的,' . $cont . '');
        }
        return $data;
    }

    public function postdata($mod, $act, $can = array())
    {
        $url = $this->geturlstr($mod, $act);
        $cont = c('curl')->postcurl($url, $can);
        if (!isempt($cont) && contain($cont, 'success')) {
            $data = json_decode($cont, true);
        } else {
            $data = returnerror('无法访问到官网API的,' . $cont . '');
        }
        return $data;
    }

    public function send($tomobile, $qiannum, $tplnum, $params = array(), $url = '', $addlog = true)
    {
        if (isempt($qiannum)) $qiannum = $this->qiannum;
        if (!isempt($this->sendtype)) {
            if (!isset($params['url']) && $url) $params['url'] = $url;
            $barr = c($this->sendtype)->send($tomobile, $qiannum, $tplnum, $params);
        } else {
            $para['sys_tomobile'] = $tomobile;
            $para['sys_tplnum'] = $tplnum;
            $para['sys_qiannum'] = $qiannum;
            $para['sys_url'] = $this->rock->jm->base64encode($url);
            foreach ($params as $k => $v) $para['can_' . $k . ''] = $v;
            $barr = $this->postdata('sms', 'send', $para);
        }
        if (!$barr['success'] && $addlog) m('log')->addlogs('短信', $barr['msg'], 2);
        return $barr;
    }

    public function sendsms($receid, $qiannum, $tplnum, $params = array(), $url = '', $addlog = true, $isyb = true)
    {
        if (isempt($receid)) return returnerror('没有接收人');
        $receda = explode(',', $receid);
        if (c('check')->iscnmobile($receda[0])) {
            $tomobile = $receid;
        } else {
            $tomobile = m('admin')->getjoinfields($receid, 'mobile');
        }
        if (isempt($tomobile)) return returnerror('接收人[' . $receid . ']可能没设置手机号');
        $toama = explode(',', $tomobile);
        $toarr = array();
        foreach ($toama as $tostr) if (!contain($tostr, '000000')) $toarr[] = $tostr;
        if (!$toarr) return returnerror('接收人的手机号不完整');
        $tomobile = join(',', $toarr);
        if (isempt($qiannum)) $qiannum = $this->qiannum;
        if (getconfig('asynsend') && $isyb) {
            $ybbo = m('reim')->asynurl('asynrun', 'sendsms', array('tomobile' => $tomobile, 'qiannum' => $qiannum, 'tplnum' => $tplnum, 'url' => $this->rock->jm->base64encode($url), 'params' => $this->rock->jm->base64encode(json_encode($params)),));
            if ($ybbo) return returnsuccess('异步发送');
        }
        return $this->send($tomobile, $qiannum, $tplnum, $params, $url, $addlog);
    }

    public function sendanay($m, $a, $can = array(), $runtime = 0)
    {
        $runurl = m('base')->getasynurl($m, $a, $can, 1);
        $barr = $this->sendanayurl($runurl, $runtime);
        return $barr;
    }

    public function sendanayurl($runurl, $runtime = 0)
    {
        if (isempt($runurl)) return returnerror('异步调用地址不能为空');
        $para = array('runurl' => $this->rock->jm->base64encode($runurl), 'runtime' => $runtime,);
        $barr = $this->postdata('anay', 'send', $para);
        if (!$barr['success']) m('log')->addlogs('调用官网异步', $barr['msg'], 2);
        return $barr;
    }

    public function getvercode($tomobile, $device, $tplnum = '', $qiannum = '')
    {
        if (isempt($tomobile)) return returnerror('接收手机号不能为空');
        if ($tplnum == '') $tplnum = m('option')->getval('sms_yanzm');
        if (isempt($tplnum)) $tplnum = 'defyzm';
        $otme = 0;
        $lorsr = m('log')->getone("`type`='获取验证码' and (`optname`='$tomobile' or `device`='$device')", '`optdt`', 'id desc');
        if ($lorsr) $otme = strtotime($lorsr['optdt']);
        $jgtims = 60;
        $jgtime = time() - $otme;
        if ($otme > 0 && $jgtime < $jgtims) return returnerror('获取太频繁,请' . ($jgtims - $jgtime) . '秒后在试');
        $code = '5' . rand(10000, 99999);
        $params['code'] = $code;
        $kaifbo = (getconfig('systype') == 'dev' || getconfig('systype') == 'demo');
        if (!$kaifbo) {
            $barr = $this->send($tomobile, $qiannum, $tplnum, $params);
        } else {
            $barr = returnsuccess('ok');
        }
        if ($barr['success']) {
            m('log')->addlog('获取验证码', '获取验证码为：' . $code . '', array('device' => $device, 'optname' => $tomobile, 'optid' => $code));
            $barr['data'] = '';
            if ($kaifbo) $barr['data'] = $code;
        }
        return $barr;
    }

    public function checkcode($tomobile, $code, $device)
    {
        if (isempt($tomobile)) return returnerror('手机号不能为空');
        if (isempt($code)) return returnerror('验证码不能为空');
        $youxiaq = 5 * 60;
        $optdt = date('Y-m-d H:i:s', time() - $youxiaq);
        $ors = m('log')->getone("`type`='获取验证码' and `optname`='$tomobile' and `device`='$device' and `optdt`>'$optdt'", '`optid`,`optdt`,`id`', '`id` desc');
        if (!$ors) return returnerror('请先获取验证码');
        if ($code != $ors['optid']) return returnerror('验证码错误');
        m('log')->update('`optid`=0', $ors['id']);
        return returnsuccess('ok');
    }

    public function starttask()
    {
        $turl = getconfig('anayurl', URL);
        $url = '' . $turl . 'task.php?m=runt&a=task';
        $barr = $this->postdata('anay', 'starttask', array('runurl' => $this->rock->jm->base64encode($url)));
        return $barr;
    }

    public function stoptask()
    {
        $barr = $this->getdata('anay', 'stoptask');
        return $barr;
    }

    public function officesend($fileid, $lx = 0)
    {
        $yulx = ',doc,docx,xls,xlsx,ppt,pptx,';
        $frs = m('file')->getone($fileid);
        if (!$frs) return returnerror('文件不存在1');
        $filepath = $frs['filepath'];
        $fileext = $frs['fileext'];
        $filepathout = arrvalue($frs, 'filepathout');
        $filesize = floatval($frs['filesize']);
        if (!contain($yulx, ',' . $fileext . ',')) return returnerror('不是文档类型');
        if (isempt($filepath)) return returnerror('文件路径是空的');
        if (substr($filepath, 0, 4) != 'http' && isempt($filepathout) && !file_exists($filepath)) return returnerror('文件不存在2');
        $pdfpath = $frs['pdfpath'];
        if (!isempt($pdfpath) && file_exists($pdfpath)) return returnerror('已转过了');
        $localpath = $frs['filepath'];
        if (substr($filepath, 0, 4) != 'http' && !isempt($filepathout) && !file_exists($filepath)) return returnerror('文件同步到其他平台无法转化预览');
        if (substr($filepath, 0, 4) == 'http') {
            $localpath = '' . UPDIR . '/' . date('Y-m') . '/' . date('d_His') . '' . rand(10, 99) . '_temp.' . $fileext . '';
            $this->rock->createtxt($localpath, @file_get_contents($filepath));
            if (!file_exists($localpath)) return returnerror('无法下载远程文件，不能转换');
            $filesize = filesize($localpath);
            if ($filesize == 0) return returnerror('远程文件已损坏');
        }
        $officeyl = getconfig('officeyl');
        $cache = c('cache');
        $zhkey = 'filetopdf' . $fileid . '';
        $zhval = $cache->get($zhkey);
        if (isempt($zhval)) {
            if ($officeyl == '1') {
                $barr = $this->postdata('office', 'recedata', array('data' => $this->rock->jm->base64encode(file_get_contents($localpath)), 'fileid' => $fileid, 'fileext' => $fileext, 'filesize' => $filesize, 'filesizecn' => $frs['filesizecn'], 'backurl' => $this->rock->jm->base64encode(m('base')->getasynurl('asynrun', 'gwpdf', array('fileid' => $fileid), 2))));
            } else if ($officeyl == '4') {
                $barr = c('libreoffice')->filetopdf($fileid);
            } else {
                if (!contain(PHP_OS, 'WIN')) return returnerror('只能在windows的服务器下转化');
                $bo = c('socket')->topdf($localpath, $fileid, $fileext);
                if (!$bo || is_string($bo)) return returnerror('' . $bo . '，' . c('xinhu')->helpstr('topdf') . '');
                $barr = returnsuccess();
            }
        } else {
            $barr = returnsuccess();
        }
        if ($barr['success']) {
            $times = ceil($filesize / (20 * 1024)) + 10;
            if ($times < 10) $times = 10;
            $cache->set($zhkey, 'true', $times + 5);
            if (!is_array($barr['data'])) $barr['data'] = array();
            $barr['data']['times'] = $times;
            $barr['data']['localpath'] = $this->rock->jm->base64encode($localpath);
        }
        return $barr;
    }

    public function officestatus($fileid)
    {
        if (getconfig('officeyl') == '1') {
            $barr = $this->getdata('office', 'getstatus', array('fileid' => $fileid));
        } else {
            $frs = m('file')->getone($fileid);
            if (!$frs) return returnerror('文件不存在1');
            $filepath = $frs['filepath'];
            $localpath = $this->rock->get('localpath');
            if (!isempt($localpath)) {
                $filepath = $this->rock->jm->base64decode($localpath);
            }
            $pdfpath = str_replace('.' . $frs['fileext'] . '', '.pdf', $filepath);
            $status = 0;
            if (file_exists($pdfpath)) {
                $status = 1;
            }
            if ($status == 1) {
                m('file')->update(array('pdfpath' => $pdfpath), $fileid);
            }
            $barr = returnsuccess(array('status' => $status, 'ftype' => '0'));
        }
        return $barr;
    }

    public function officedown($fileid)
    {
        $barr = $this->getdata('office', 'down', array('fileid' => $fileid));
        if ($barr['success']) {
            $data = $barr['data'];
            $pdfpath = $data['pdfpath'];
            $this->rock->createtxt($pdfpath, $this->rock->jm->base64decode($data['data']));
            m('file')->update(array('pdfpath' => $pdfpath,), $fileid);
            $barr = returnsuccess();
        }
        return $barr;
    }

    public function getjiari()
    {
        $barr = $this->getdata('base', 'getjiari');
        return $barr;
    }

    public function authercheck($key, $ym)
    {
//        if (isempt($key)) return returnerror('密钥格不能为空');
//        if (isempt($ym)) return returnerror('域名不能为空');
//        $barr = $this->getdata('auther', 'check', array('autherkey' => $key, 'yuming' => $ym, 'randkey' => getconfig('randkey')));
//        if ($barr['success']) {
//            $da = $barr['data'];
        if (isempt($key)) {
            $key = "a97536d5d0e9b7583214aae489f44247";
        }
        $da = [
            'enddt' => $this->rock->jm->encrypts('2099-12-31'),
            'yuming' => $this->rock->jm->encrypts('oa.dutuwang.net'),
            'authkey' => $this->rock->jm->encrypts($key),
        ];

            $this->saveauther($da, $key);
            return returnsuccess();
//        } else {
//            return $barr;
//        }
    }

    private function saveauther($da, $key)
    {
        $db = m('option');
        $db->setval('auther_enddt@-101', $da['enddt']);
        $db->setval('auther_yuming@-101', $da['yuming']);
        $db->setval('auther_authkey@-101', $da['authkey']);
        $db->setval('auther_aukey@-101', $key);
        m('chargems')->update("`updatedt`='2020-02-02 02:02:02'", "`type`=0 and `mid` in(1,22)");
    }

    public function autherfile($da, $key, $ym)
    {
        $da['enddt'] = $this->rock->jm->encrypt($this->rock->jm->strunlook($da['enddt'], $key));
        $yuming = $this->rock->jm->strunlook($da['yuming'], $key);
        $xhkey1 = $this->rock->jm->strunlook($da['xhkey'], $key);
        $da['yuming'] = $this->rock->jm->encrypt($yuming);
        $da['authkey'] = $this->rock->jm->base64encode($this->rock->jm->strunlook($da['authkey'], $key));
        $xhkey = getconfig('xinhukey');
        if (isempt($xhkey)) return returnerror($this->rock->jm->base64decode('6K!35YWI5Yiw57O757uf6K6!572u5LiL6K6!572u5L!h5ZG85a6Y572Ra2V5'));
        if ($xhkey1 != $xhkey) return returnerror($this->rock->jm->base64decode('5L!h5ZG85a6Y572Ra2V55LiN5LiA6Ie077yM6K!36YeN5paw6K6!572u'));
        if (!contain(',' . $yuming . ',', ',' . $ym . ',')) return returnerror('' . $ym . '不在签授域名里');
        $this->saveauther($da, $key);
        return returnsuccess();
    }

    public function autherdel()
    {
        $aukey = m('option')->getval('auther_aukey');
        m('option')->update('`value`=null', 'pid=-101');
        if (!isempt($aukey)) {
            $barr = $this->getdata('auther', 'delkey', array('autherkey' => $aukey, 'randkey' => getconfig('randkey')));
            return $barr;
        }
        return returnsuccess();
    }
}